package com.qdsgjsfk.vision.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.qdsgjsfk.vision.R;
import com.qdsgjsfk.vision.base.BaseApplication;
import com.qdsgjsfk.vision.util.ToastUtil;
import com.rest.business.RestProxy;
import com.rest.response.AxisResponse;
import com.rest.response.IsTaskDataResponse;
import com.rest.response.TaskListResponse;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.BallPulseFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import jz.joyoung.robot.util.LogUtil;

import com.qdsgjsfk.vision.base.BaseActivity;
import com.qdsgjsfk.vision.util.NetUtil;

/**
 * Created by HP on 2019/9/2.
 */

public class SearchActivity extends BaseActivity {

    @BindView(R.id.recyclerView_student_list)
    RecyclerView recyclerView_student_list;
    @BindView(R.id.refreshLayout)
    RefreshLayout refreshLayout;

    @BindView(R.id.ed_search)
    EditText ed_search;
    @BindView(R.id.tv_task)
    TextView tv_task;
    MyAdapter myAdapter;
    Bundle bundle;
    List<TaskListResponse.Task> list = new ArrayList<>();
    private int currentPage = 1;

    @Override
    protected void initViews() {
        myAdapter = new MyAdapter();
        recyclerView_student_list.setLayoutManager( new LinearLayoutManager( this ) );
        recyclerView_student_list.setAdapter( myAdapter );
        refreshLayout.setRefreshFooter( new BallPulseFooter( this ).setSpinnerStyle( SpinnerStyle.Scale ) );
        refreshLayout.setRefreshHeader( new ClassicsHeader( this ) );
        refreshLayout.setEnableLoadMore( true );
        refreshLayout.setOnRefreshListener( refreshlayout -> getTaskList(false) );
        refreshLayout.setOnLoadMoreListener( refreshlayout -> {
            getTaskList(true);
        } );
        ed_search.setOnEditorActionListener( (v, actionId, event) -> {
            hintKeyBoard( ed_search );
            getTaskList(false);
            return true;
        } );
    }

    @Override
    protected void initData() {

    }

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_search_task;
    }


    class MyAdapter extends RecyclerView.Adapter<MyAdapter.TaskHolder> {
        int checkPosition = -1;

        @Override
        public MyAdapter.TaskHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new MyAdapter.TaskHolder( getLayoutInflater().inflate( R.layout.item_task, parent, false ) );
        }

        @Override
        public void onBindViewHolder(MyAdapter.TaskHolder holder, final int position) {
            holder.tv_project.setText( list.get( position ).checkOption );
            holder.tv_date.setText( list.get( position ).taskTime );
            holder.tv_school.setText( list.get( position ).taskOrgName );
            holder.tv_worker.setText( list.get( position ).workers );
            holder.tv_twice.setText( list.get( position ).planName );
            String status = list.get( position ).status;
            String planType = list.get( position ).planType;
            //筛查状态 status  ：  0 待筛查  1 已筛查 2-全部
            if ("0".equals( status )) {
                holder.tv_status.setTextColor( ContextCompat.getColor( SearchActivity.this, R.color.FF932D ) );
                holder.tv_status.setText( "进行中" );
            } else if ("1".equals( status )) {
                holder.tv_status.setTextColor( ContextCompat.getColor( SearchActivity.this, R.color.commonGrey ) );
                holder.tv_status.setText( "已完成" );
            }
            //计划类型： 101-普查计划 102-抽查计划 103-复查计划
            if ("101".equals( planType )) {
                holder.tv_plan_type.setText( "普查" );
            } else if ("102".equals( planType )) {
                holder.tv_plan_type.setText( "抽查" );
            } else if ("103".equals( planType )) {
                holder.tv_plan_type.setText( "复查" );
            } else if ("104".equals( planType )) {
                holder.tv_plan_type.setText( "自查" );
            }
//                ((StudentHolder) holder).progressSelf.setProgress(listWithLetter.get(position).schedule);
//                ((StudentHolder) holder).examinationDate.setText(listWithLetter.get(position).examinationDate);
            holder.itemView.setOnClickListener( v -> {
                bundle = new Bundle();
                bundle.putString( "taskSchoolId", list.get( position ).taskOrgId );
                bundle.putString( "taskId", list.get( position ).taskId );
                bundle.putString( "schoolName", list.get( position ).taskOrgName );
                isTask( list.get( position ).taskId );
//                    showSchoolDialog(list.get(position).taskSchoolId,list.get(position).taskId,list.get(position).schoolName);
            } );
            holder.ll_open_close.setOnClickListener( new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (checkPosition == position) {
                        if (holder.ll_project.getVisibility() == View.VISIBLE) {
                            holder.ll_project.setVisibility( View.GONE );
                            holder.iv_open_close.setImageDrawable( ContextCompat.getDrawable( SearchActivity.this, R.mipmap.icon_open ) );
                        } else {
                            holder.ll_project.setVisibility( View.VISIBLE );
                            holder.iv_open_close.setImageDrawable( ContextCompat.getDrawable( SearchActivity.this, R.mipmap.icon_close_task ) );
                        }

                    } else {
                        if (holder.ll_project.getVisibility() == View.VISIBLE) {
                            holder.ll_project.setVisibility( View.GONE );
                            holder.iv_open_close.setImageDrawable( ContextCompat.getDrawable( SearchActivity.this, R.mipmap.icon_open ) );
                        } else {
                            holder.ll_project.setVisibility( View.VISIBLE );
                            holder.iv_open_close.setImageDrawable( ContextCompat.getDrawable( SearchActivity.this, R.mipmap.icon_close_task ) );
                        }
                    }
                    checkPosition = position;
                }
            } );
        }


        @Override
        public int getItemCount() {
            return list.size();
        }


        class TaskHolder extends RecyclerView.ViewHolder {
            TextView tv_project, tv_school, tv_worker, tv_date, tv_twice, tv_status, tv_plan_type;
            LinearLayout ll_open_close, ll_project;
            ImageView iv_open_close;

            public TaskHolder(View itemView) {
                super( itemView );
                tv_project = itemView.findViewById( R.id.tv_project );
                tv_school = itemView.findViewById( R.id.tv_school );
                tv_worker = itemView.findViewById( R.id.tv_worker );
                tv_date = itemView.findViewById( R.id.tv_date );
                tv_twice = itemView.findViewById( R.id.tv_twice );
                tv_status = itemView.findViewById( R.id.tv_status );
                tv_plan_type = itemView.findViewById( R.id.tv_plan_type );
                ll_open_close = itemView.findViewById( R.id.ll_open_close );
                ll_project = itemView.findViewById( R.id.ll_project );
                iv_open_close = itemView.findViewById( R.id.iv_open_close );
            }
        }


    }


    private void getTaskList(Boolean loadMore) {
        if (loadMore){
            currentPage ++;
        }else {
            currentPage = 1;
        }
        RestProxy.getInstance().getTaskList( currentPage,"", ed_search.getText().toString().trim(), "", "", "", "", new Observer<TaskListResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(TaskListResponse taskListResponse) {
                if (loadMore){
                    refreshLayout.finishLoadMore();
                }else {
                    refreshLayout.finishRefresh();
                }
                try {
                    if (taskListResponse.data != null && taskListResponse.data.list != null) {
                        if (loadMore){
                            if (taskListResponse.data.list.size() > 0) {
                                tv_task.setVisibility( View.GONE );
                                recyclerView_student_list.setVisibility( View.VISIBLE );
                                list.addAll( taskListResponse.data.list );
                                myAdapter.notifyDataSetChanged();
                            }else {
                                ToastUtil.showToast(SearchActivity.this,"没有更多数据");
                            }
                        }else {
                        if (taskListResponse.data.list.size() > 0) {
                            tv_task.setVisibility( View.GONE );
                            recyclerView_student_list.setVisibility( View.VISIBLE );
                            list.clear();
                            list.addAll( taskListResponse.data.list );
                            myAdapter.notifyDataSetChanged();
                        } else {
                            tv_task.setVisibility( View.VISIBLE );
                            recyclerView_student_list.setVisibility( View.GONE );
                        }
                    }
                    }

                } catch (Exception e) {
                    // 捕获异常，如果要捕获Json数据异常，写catch(JSONException e)
                    e.printStackTrace();
                    //打印出来就Log.e(TAG,Log.getStackTraceString(e));
                    //如果JSONException e，打印出来就 Log.e(TAG, e.toString() + "");
                }

            }

            @Override
            public void onError(Throwable e) {
                if (loadMore){
                    currentPage --;
                }
                e.printStackTrace();
                NetUtil.onError( e, SearchActivity.this );
                refreshLayout.finishRefresh();
            }

            @Override
            public void onComplete() {
                refreshLayout.finishRefresh();
            }
        } );
    }


    private void isTask(String taskId) {
        RestProxy.getInstance().isTask( taskId, new Observer<IsTaskDataResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(IsTaskDataResponse isTaskDataResponse) {
                if (isTaskDataResponse.data == 1) {

                    RestProxy.getInstance().isShowOther( taskId, new Observer<AxisResponse>() {


                        @Override
                        public void onSubscribe(Disposable d) {

                        }

                        @Override
                        public void onNext(AxisResponse axisResponse) {
                            LogUtil.e( "配置其他项" + axisResponse.data.other + "--" + axisResponse.data.Axis );
                            BaseApplication.isShowOther = axisResponse.data.other;
                            BaseApplication.isShowAxis = axisResponse.data.Axis;
                            Intent mIntent = new Intent();
                            mIntent.putExtra( "taskSchoolId", bundle.getString( "taskSchoolId" ) );
                            mIntent.putExtra( "taskId", bundle.getString( "taskId" ) );
                            mIntent.putExtra( "schoolName", bundle.getString( "schoolName" ) );
                            setResult( Activity.RESULT_OK, mIntent );
                            finish();
                        }

                        @Override
                        public void onError(Throwable e) {
                            e.printStackTrace();
                            NetUtil.onError( e, mContext );
                        }

                        @Override
                        public void onComplete() {

                        }
                    } );

//                    showSchoolDialog(bundle.getString("taskSchoolId"),bundle.getString("taskId"),bundle.getString("schoolName"));
//                    startActivity(ClassActivity.class, bundle);
                } else if (isTaskDataResponse.data == 0) {
                    Toast.makeText( SearchActivity.this, "任务未开始！", Toast.LENGTH_SHORT ).show();
                } else if (isTaskDataResponse.data == 2) {
                    Toast.makeText( SearchActivity.this, "任务已结束！", Toast.LENGTH_SHORT ).show();
                }
            }

            @Override
            public void onError(Throwable e) {
                NetUtil.onError( e, SearchActivity.this );
            }

            @Override
            public void onComplete() {

            }
        } );
    }

}
